package com.lfg.leetcode.leetcode200;

public class No200numIslands {

    public static void main(String[] args) {
        int ret = numIslands(new char[][]{
                new char[]{'1', '0', '1', '0', '0'},
                new char[]{'0', '1', '0', '1', '0'},
                new char[]{'1', '1', '0', '0', '0'},
                new char[]{'0', '0', '1', '0', '1'}
        });

        System.out.println(ret);
    }


    public static int numIslands(char[][] grid) {
        int ret = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[i].length; j++) {
                if (grid[i][j] == '1') {
                    ret++;
                    updateGrid(grid, i, j);
                }
            }
        }
        return ret;
    }

    public static void updateGrid(char[][] grid, int i, int j) {
        if (grid[i][j] != '1') {
            return;
        }
        grid[i][j] = 2;
        if (i > 0) {
            updateGrid(grid, i - 1, j);
        }
        if (i < grid.length - 1) {
            updateGrid(grid, i + 1, j);
        }
        if (j > 0) {
            updateGrid(grid, i, j - 1);
        }
        if (j < grid[i].length - 1) {
            updateGrid(grid, i, j + 1);
        }
    }
}
